<template>
  <view class="route-management-page">
    <!-- 导航栏 -->
    <u-navbar title="路线管理" back-icon="arrow-left" />
    
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <u-input
          v-model="filterForm.routeName"
          placeholder="请输入路线名称"
          class="filter-input"
          @input="handleSearch"
        />
        <u-button 
          type="primary" 
          text="搜索" 
          size="mini"
          @click="handleSearch"
        />
      </view>
      <view class="filter-row">
        <u-picker
          :show="showCommunityPicker"
          :columns="communityColumns"
          @confirm="onCommunityConfirm"
          @cancel="showCommunityPicker = false"
          title="选择所属社区"
        />
        <u-input
          v-model="filterForm.communityName"
          placeholder="所属社区"
          readonly
          @click="showCommunityPicker = true"
          class="filter-input"
        />
        <u-picker
          :show="showTypePicker"
          :columns="typeColumns"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
          title="选择路线类型"
        />
        <u-input
          v-model="filterForm.routeTypeText"
          placeholder="路线类型"
          readonly
          @click="showTypePicker = true"
          class="filter-input"
        />
      </view>
      <view class="filter-row">
        <u-picker
          :show="showStatusPicker"
          :columns="statusColumns"
          @confirm="onStatusConfirm"
          @cancel="showStatusPicker = false"
          title="选择状态"
        />
        <u-input
          v-model="filterForm.statusText"
          placeholder="状态"
          readonly
          @click="showStatusPicker = true"
          class="filter-input"
        />
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view 
      scroll-y="true" 
      class="list-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <!-- 路线列表 -->
        <view 
          v-for="item in routeList" 
          :key="item.id"
          class="route-card"
          @click="goToRouteDetail(item.id)"
        >
          <view class="card-header">
            <view class="header-left">
              <text class="route-name">{{ item.routeName }}</text>
              <u-tag 
                :text="getRouteTypeText(item.routeType)" 
                type="info" 
                size="mini"
                class="type-tag"
              />
            </view>
            <view class="header-right">
              <u-tag 
                :text="getStatusText(item.status)" 
                :type="getStatusType(item.status)" 
                size="mini"
              />
            </view>
          </view>
          
          <view class="card-content">
            <view class="content-item" v-if="item.description">
              <u-icon name="file-text" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.description }}</text>
            </view>
            <view class="content-item">
              <u-icon name="clock" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ getFrequencyText(item.frequency) }}</text>
            </view>
            <view class="content-item" v-if="item.durationMinutes">
              <u-icon name="time" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">预计用时：{{ item.durationMinutes }}分钟</text>
            </view>
            <view class="content-item" v-if="item.checkpoints">
              <u-icon name="map-pin" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">检查点：{{ getCheckpointsCount(item.checkpoints) }}个</text>
            </view>
          </view>
          
          <view class="card-footer">
            <text class="create-time">{{ formatTime(item.createTime) }}</text>
            <view class="action-buttons">
              <u-button 
                type="primary" 
                text="编辑"
                size="mini"
                @click.stop="goToRouteEdit(item.id)"
                class="action-btn"
              />
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="routeList.length === 0 && !loading" class="empty-state">
          <u-empty text="暂无路线数据" icon="map" mode="list" />
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="routeList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 添加按钮 -->
    <view class="add-button" @click="goToRouteAdd">
      <u-icon name="plus" color="#fff" size="24"></u-icon>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getSecurityRoutePage } from '@/api/security'
import { commonApi } from '@/api/property'

// 响应式数据
const routeList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  routeName: '',
  communityId: '',
  communityName: '',
  routeType: '',
  routeTypeText: '',
  status: '',
  statusText: ''
})

// 选择器显示状态
const showCommunityPicker = ref(false)
const showTypePicker = ref(false)
const showStatusPicker = ref(false)

// 选择器数据
const communityList = ref([])
const communityColumns = ref([[]])

const typeColumns = ref([[
  { label: '巡逻路线', value: 'patrol' },
  { label: '检查点', value: 'checkpoint' }
]])

const statusColumns = ref([[
  { label: '启用', value: 1 },
  { label: '停用', value: 2 }
]])

// 页面加载时获取数据
onMounted(() => {
  loadCommunityList()
  loadRouteList()
})

/**
 * 加载路线列表
 */
const loadRouteList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      pagination.pageNum = 1
      routeList.value = []
      hasMore.value = true
    }
    
    loading.value = true
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      routeName: filterForm.routeName,
      communityId: filterForm.communityId,
      routeType: filterForm.routeType,
      status: filterForm.status
    }
    
    const response = await getSecurityRoutePage(params)
    if (response.success && response.data) {
      const { records, total } = response.data
      
      if (isRefresh) {
        routeList.value = records || []
      } else {
        routeList.value.push(...(records || []))
      }
      
      pagination.total = total || 0
      hasMore.value = routeList.value.length < pagination.total
    }
  } catch (error) {
    console.error('加载路线列表失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 加载社区列表
 */
const loadCommunityList = async () => {
  try {
    const response = await commonApi.getCommunityList()
    console.log('社区列表API响应:', response)
    
    if (response.success && response.data) {
      // 确保response.data是数组
      const data = Array.isArray(response.data) ? response.data : []
      communityList.value = data
      
      // 构建选择器数据
      communityColumns.value = [[
        { label: '全部社区', value: '' },
        ...data.map(community => ({
          label: community.communityName || community.name || '未知社区',
          value: community.id || community.communityId
        }))
      ]]
      console.log('社区列表加载成功:', communityList.value)
    } else {
      console.warn('社区列表API返回数据为空或失败:', response)
      communityList.value = []
      communityColumns.value = [[{ label: '全部社区', value: '' }]]
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    communityList.value = []
    communityColumns.value = [[{ label: '全部社区', value: '' }]]
    uni.showToast({
      title: '加载社区列表失败',
      icon: 'none'
    })
  }
}

/**
 * 社区选择确认
 */
const onCommunityConfirm = (event) => {
  const selectedCommunity = event.value[0]
  filterForm.communityId = selectedCommunity.value
  filterForm.communityName = selectedCommunity.label
  showCommunityPicker.value = false
  loadRouteList(true)
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  loadRouteList(true)
}

/**
 * 类型选择确认
 */
const onTypeConfirm = (event) => {
  const selectedType = event.value[0]
  filterForm.routeType = selectedType.value
  filterForm.routeTypeText = selectedType.label
  showTypePicker.value = false
  loadRouteList(true)
}

/**
 * 状态选择确认
 */
const onStatusConfirm = (event) => {
  const selectedStatus = event.value[0]
  filterForm.status = selectedStatus.value
  filterForm.statusText = selectedStatus.label
  showStatusPicker.value = false
  loadRouteList(true)
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  refreshing.value = true
  loadRouteList(true)
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pagination.pageNum++
    loadRouteList()
  }
}

/**
 * 获取路线类型文本
 */
const getRouteTypeText = (type) => {
  const typeMap = {
    'patrol': '巡逻',
    'checkpoint': '检查点'
  }
  return typeMap[type] || '未知类型'
}

/**
 * 获取频次文本
 */
const getFrequencyText = (frequency) => {
  const frequencyMap = {
    'hourly': '每小时',
    'every_2_hours': '每2小时',
    'daily': '每日'
  }
  return frequencyMap[frequency] || '未知频次'
}

/**
 * 获取检查点数量
 */
const getCheckpointsCount = (checkpoints) => {
  if (!checkpoints) return 0
  try {
    const data = typeof checkpoints === 'string' ? JSON.parse(checkpoints) : checkpoints
    return Array.isArray(data) ? data.length : 0
  } catch (error) {
    return 0
  }
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '启用',
    2: '停用'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const typeMap = {
    1: 'success',
    2: 'error'
  }
  return typeMap[status] || 'info'
}

/**
 * 格式化时间
 */
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 页面导航方法
const goToRouteDetail = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/route-detail?id=${id}`
  })
}

const goToRouteEdit = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/route-edit?id=${id}`
  })
}

const goToRouteAdd = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/route-add'
  })
}
</script>

<style lang="scss" scoped>
.route-management-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-input {
      flex: 1;
    }
  }
}

.list-scroll {
  flex: 1;
  min-height: 0;
}

.list-content {
  padding: 20rpx;
}

.route-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .route-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .type-tag {
        flex-shrink: 0;
      }
    }
  }
  
  .card-content {
    margin-bottom: 20rpx;
    
    .content-item {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .item-icon {
        flex-shrink: 0;
      }
      
      .item-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        word-break: break-all;
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .create-time {
      font-size: 24rpx;
      color: #999;
    }
    
    .action-buttons {
      .action-btn {
        min-width: 120rpx;
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.add-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.4);
  z-index: 999;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}
</style>
